//
//  RetrievingPWDViewController.m
//  NiuBanJin
//
//  Created by zf on 15/10/16.
//  Copyright © 2015年 zzjr. All rights reserved.
//

#import "RetrievingPWDViewController.h"
#import "UsefulUtil.h"

@interface RetrievingPWDViewController ()<UITextFieldDelegate , UIAlertViewDelegate>
@property (nonatomic , strong) NSArray *array_labelText;
@property (nonatomic , strong) NSArray *array_fieldText;
@end

@implementation RetrievingPWDViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"忘记转出密码";
    self.view.backgroundColor = BASECOLOR;
    self.array_labelText = @[@"验证码" , @"新密码", @"新密码"];
    self.array_fieldText = @[@"请输入4位短信验证码"  , @"请输入新转出密码" ,@"请再次输入新转出密码"];
    
    UILabel *label_bindPhone = [[UILabel alloc]initWithFrame:CGRectMake(MULTIPLYWIDTH(15), 0 , MULTIPLYWIDTH(300), MULTIPLYHEIGHT(50))];
    label_bindPhone.font = [UIFont systemFontOfSize:15.0];
    label_bindPhone.textColor = [UsefulUtil colorWithHexString:@"#434343"];
    //    UITextField *field_phone = [[UITextField alloc]initWithFrame:CGRectMake(MULTIPLYWIDTH(100), 0 , MULTIPLYWIDTH(80), MULTIPLYHEIGHT(50))];
    
    
    NSString *str_phone = GETCURRENTUSERINOBYPRAMETERES(user_userName);
    label_bindPhone.text = [NSString stringWithFormat:@"绑定手机       %@",str_phone];
    [self.view addSubview:label_bindPhone];
    //    [self.view addSubview:field_phone];
    for (int i = 0 ; i < 3; i++) {
        
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, MULTIPLYHEIGHT(70)* i +  MULTIPLYHEIGHT(50) , self.view.frame.size.width, MULTIPLYHEIGHT(50))];
        view.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:view];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(MULTIPLYWIDTH(15), MULTIPLYHEIGHT(70)* i +  MULTIPLYHEIGHT(50) , MULTIPLYWIDTH(80), MULTIPLYHEIGHT(50))];
        label.text = [self.array_labelText objectAtIndex:i];
        label.font = [UIFont systemFontOfSize:15.0];
        label.textColor = [UsefulUtil colorWithHexString:@"#434343"];
        [self.view addSubview:label];
        
        BCTextField *field = [[BCTextField alloc]initWithFrame:CGRectMake(MULTIPLYWIDTH(100), CGRectGetMinY(label.frame) + MULTIPLYHEIGHT(2.0) , MULTIPLYWIDTH(180), MULTIPLYHEIGHT(50))];
        [field setRegx:@"^[0-9]{0,6}$"];
//        field.clearButtonMode = UITextFieldViewModeNever;
        field.font = [UIFont systemFontOfSize:15.0];
        field.adjustsFontSizeToFitWidth = YES;
        field.delegate = self;
        field.placeholder = [self.array_fieldText objectAtIndex:i];
        field.keyboardType = UIKeyboardTypeNumberPad;
        field.tag = 100 + i;
        field.secureTextEntry = YES;
        [self.view addSubview:field];
    }
    
    
    UIButton *button_modifyPWD = [UIButton buttonWithType:UIButtonTypeSystem];
    button_modifyPWD.frame = CGRectMake(MULTIPLYWIDTH(15),  MULTIPLYHEIGHT(240) + MULTIPLYHEIGHT(62.0 /2), self.view.frame.size.width - MULTIPLYWIDTH(30), MULTIPLYHEIGHT(45));
    button_modifyPWD.backgroundColor = [UIColor redColor];
    [button_modifyPWD setTitle:@"提交" forState:UIControlStateNormal];
    [button_modifyPWD addTarget:self action:@selector(commitAction) forControlEvents:UIControlEventTouchUpInside];
    button_modifyPWD.titleLabel.font = [UIFont systemFontOfSize:15.0 ];//粗体
    button_modifyPWD.tintColor = [UIColor whiteColor];
    [self.view addSubview:button_modifyPWD];
    
    UIButton *button_getAuthenticationCode = [[UIButton alloc]init];
    button_getAuthenticationCode.frame = CGRectMake(MULTIPLYWIDTH(280), MULTIPLYHEIGHT(50), MULTIPLYWIDTH(90), MULTIPLYHEIGHT(50));
    button_getAuthenticationCode.tag = 550;
    [button_getAuthenticationCode addTarget:self action:@selector(getCode:) forControlEvents:UIControlEventTouchUpInside];
    [button_getAuthenticationCode setTitle:@"获取验证码" forState:UIControlStateNormal];
    [button_getAuthenticationCode setTitleColor:[UsefulUtil colorWithHexString:@"#4fa6fd"] forState:UIControlStateNormal];
    [button_getAuthenticationCode setTitle:@"获取验证码" forState:UIControlStateNormal];
    button_getAuthenticationCode.titleLabel.font = [UIFont systemFontOfSize:15.0];

    button_getAuthenticationCode.titleLabel.adjustsFontSizeToFitWidth = YES;
    [self.view addSubview:button_getAuthenticationCode];
    
    
    UIImageView *imageView_telePhone = [[UIImageView alloc]init];
    imageView_telePhone.image = [UIImage imageNamed:@"telephone"];
    imageView_telePhone.frame = CGRectMake(MULTIPLYWIDTH(90), CGRectGetMidY(button_modifyPWD.frame) + MULTIPLYHEIGHT(40), MULTIPLYWIDTH(10), MULTIPLYHEIGHT(15));
    UIButton *button_serverPhone = [UIButton buttonWithType:UIButtonTypeSystem];
    [button_serverPhone setTitle:@"牛板金服务热线:4001826268" forState:UIControlStateNormal] ;
    button_serverPhone.titleLabel.font = [UIFont systemFontOfSize:11.0];
    button_serverPhone.tintColor = [UsefulUtil colorWithHexString:@"5f5f61"];
    button_serverPhone.titleLabel.adjustsFontSizeToFitWidth = YES;
    button_serverPhone.frame = CGRectMake(CGRectGetMaxX(imageView_telePhone.frame),CGRectGetMidY(button_modifyPWD.frame) + MULTIPLYHEIGHT(40) , MULTIPLYWIDTH(160), MULTIPLYHEIGHT(10));
    [button_serverPhone addTarget:self action:@selector(serverAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button_serverPhone];
    [self.view addSubview:imageView_telePhone];
    
    UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeGestureAction)];
    [self.view addGestureRecognizer:swipeGesture];
    
}
#pragma mark - 限定6位输入框
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.tag == 100) {
        
        textField.secureTextEntry = NO;
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        if (existedLength - selectedLength + replaceLength > 4) {
            return NO;
            
        }
    }
    
    
    return YES;
}
#pragma mark -swipeGestureAction
-(void)swipeGestureAction{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void) countDownMethod {
    UIButton *button = (UIButton *)[self.view viewWithTag:550];
    __block int timeout = 60; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        
        if(timeout<=0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置界面的按钮显示 根据自己需求设置 特别注明：UI的改变一定要在主线程中进行
                [button setTitle:@"重新获取" forState:UIControlStateNormal];
                button.userInteractionEnabled = YES;
                
            });
        }else{
            //            int minutes = timeout / 60;
            //            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", timeout];
            NSString *strTime2 = [NSString stringWithFormat:@"%.d", timeout];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [strTime integerValue] >= 10? [button setTitle:[NSString stringWithFormat:@"重发(%@)秒",strTime] forState:UIControlStateNormal] : [button setTitle:[NSString stringWithFormat:@"重发(%@)秒",strTime2] forState:UIControlStateNormal];
                
                button.userInteractionEnabled = NO;
                
            });
            timeout--;
        }
    });
    
    dispatch_resume(_timer);
}

#pragma  mark -getCode
- (void)getCode:(UIButton *)sender  {
    sender.titleLabel.adjustsFontSizeToFitWidth = YES;
    [self countDownMethod];
    if (GETCURRENTUSERINOBYPRAMETERES(user_userName)) {
        
        NSDictionary *dic_code = @{@"mobile" : GETCURRENTUSERINOBYPRAMETERES(user_userName) ,@"type" : @"2" , @"isRetry" : @"1"};
        [[NetworkUtil sharedNetworkUtil]  zzjrGetSMSAuthenticationCodeByParmeteres:dic_code transferResultUsingBlock:^(id parsedData, NSError *error) {
            if (!error) {  //没有网络错误
                
                // 开始解析数据
                NSDictionary *dic = parsedData;
                
                if([dic[@"status"] intValue] == 0) {
                    
                    NSString *result = [NSString stringWithFormat:@"%@",dic[@"result"][@"authenticationCode"]];
                    [UsefulUtil showAlertView:[NSString stringWithFormat:@" 验证码是:%@",result]];
                } else {// 不是网络出错, 其它错误
                    
                    [UsefulUtil showAlertView:dic[@"msg"]];
                    
                }
            }else {
                
                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                [UsefulUtil showAlertView:@"遇到网络问题,请稍后重试!"];
                
            }
        }];
        
    }
    
}
#pragma mark -serverAction
-(void)serverAction {
    NSLog(@"服务热线");
    
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",@"4001826268"];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    
}
#pragma mark -commitAction
- (void)commitAction {
    NSLog(@"提交");
    
    UITextField *textField_code = (UITextField *)[self.view viewWithTag:100];
    UITextField *textField_newPWD = (UITextField *)[self.view viewWithTag:101];
    UITextField *textField_newPWD1 = (UITextField *)[self.view viewWithTag:102];
       if (textField_code.text.length != 4) {
        [UsefulUtil showAlertView:@"请输入4位验证码"];
    }
    
    if (textField_code.text.length == 4 && [textField_newPWD.text isEqualToString:textField_newPWD1.text] ) {
        
        NSDictionary *dic_reset_password = @{@"newPassword" : textField_newPWD1.text , @"authenticationCode" : textField_code.text , @"userId" : GETCURRENTUSERINOBYPRAMETERES(user_userId) , @"token" : GETCURRENTUSERINOBYPRAMETERES(user_userToken)};
        [[NETWorkingUtil sharedNETWorking] zzjrMore_reset_passwordByParmeteres:dic_reset_password transferResultUsingBlock:^(id parsedData, NSError *error) {
            if (!error) {
                
                if ([parsedData[@"status"] integerValue] == 0) {
                    
                    if ([parsedData[@"msg"] isEqualToString:@"成功"]) {
                        
                        [UsefulUtil showAlertView:parsedData[@"msg"]];
                        [self.navigationController popViewControllerAnimated:YES];
                    }else {
                        
                        [UsefulUtil showAlertView:parsedData[@"msg"]];
                    }
                    
                }else {
                    
                    [UsefulUtil showAlertView:parsedData[@"msg"]];
                }


            }else {
                
                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                [UsefulUtil showAlertView:@"遇到网络问题,请稍后重试!"];
            }
        }];
    }else {
        
        [UsefulUtil showAlertView:@"两次密码不一致,请重设密码"];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 0) {
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
